package job.work.service.auth;


import job.work.domain.response.AuthCode;
import job.work.domain.system.entity.pojo.DecMenu;
import job.work.domain.system.entity.pojo.DecRole;
import job.work.domain.system.entity.pojo.UserJwt;
import job.work.domain.system.entity.pojo.model.SystemUser;
import job.work.framework.ExceptionCast;
import job.work.service.system.service.DecMenuService;
import job.work.service.system.service.SystemService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//import com.jjmy.system.feign.DecMenuFenign;

/*****
 * 自定义授权认证类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    DecMenuService decMenuService;

    @Resource
    SystemService systemService;

    @Resource
    HttpServletRequest httpServletRequest;


    /**
     * 菜单接口
     */
//    @Autowired
//    DecMenuFenign decMenuFenign;


    /****
     * 自定义授权认证
     * @param username 用户名或者手机号
     * @return 用户详情信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StringUtils.isEmpty(username)) {
            return null;
        }
        SystemUser system = systemService.findSystemUserName(username);
        if (system == null) {
                ExceptionCast.cast(AuthCode.AUTH_ACCOUNT_NOTEXISTS);
        }
        if (system.getStatus() == 1) {
            httpServletRequest.setAttribute("10010",AuthCode.AUTH_LOGIN_TOKEN_DISABLE);
            //ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_DISABLE);
            throw new BadCredentialsException("此用户已被禁用!");
        }else{
            httpServletRequest.setAttribute("10010",AuthCode.AUTH_CREDENTIAL_ERROR);
        }
        //获取用户的信息并返回
//      return this.userInfor(system);
        return system;

    }

    /**
     * 根据手机号查询用户信息
     *
     * @param mobile 手机号
     * @return 用户信息
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        //判断手机号码是否存在
        if (StringUtils.isEmpty(mobile)) {
            ExceptionCast.cast(AuthCode.AUTH_MOBILE_ERROR);
        }
        SystemUser systemMobile = systemService.findSystemMobile(mobile);
        if (systemMobile == null) {
            ExceptionCast.cast(AuthCode.AUTH_ACCOUNT_NOTEXISTS);
        }
        //获取用户的信息并返回
        return this.userInfor(systemMobile);
    }


    /**
     * 根据用户信息 封装用户数据
     *
     * @param system 用户信息
     * @return 封装后的数据
     */
    private UserJwt userInfor(SystemUser system) {

        //获取用户角色信息
        if (system.getRoleId() == 0) {
            DecRole role = systemService.findRole(system.getRoleId());
            if (role == null) {
                ExceptionCast.cast(AuthCode.ROLE_ERROR);
            }
        }
        //根据角色获取当前用户的权限信息
        //从数据库获取权限
        List<DecMenu> permissions = decMenuService.findRoleMenu(system.getRoleId());

        List<String> userPermission = new ArrayList<>();
        Set<Long> menuId = new HashSet<>();
        permissions.forEach(item -> {
            userPermission.add(item.getUrl());
            menuId.add(item.getId());

        });
        userPermission.add("test");
        String userPermissionString = org.apache.commons.lang3.StringUtils.join(userPermission.toArray(), ",");
        UserJwt userDetails = new UserJwt(system.getUsername(), system.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(userPermissionString));
        //封装用户信息
        //用户ID
        if (system.getId() != null) {
            userDetails.setId(system.getId());
        }
        //用户头像
        if (!StringUtils.isEmpty(system.getImage())) {
            userDetails.setImage(system.getImage());
        }

        //用户手机号
        if (!StringUtils.isEmpty(system.getPhone())) {
            userDetails.setTelephone(system.getPhone());
        }
        //用户角色
        if ((system.getRoleId() != null)) {
            userDetails.setRoleId(system.getRoleId());
        }
        //用户菜单权限ID
        userDetails.setUserPermission(menuId);


        return userDetails;

    }
}
